package com.mtcarpenter.option;

import com.mtcarpenter.common.Fruit;
import org.junit.Test;

import java.util.Optional;

/**
 * @Author: mtcarpenter
 * @describe
 * @Date: 2019/10/7
 * @Version 1.0
 */
public class Option01Test {

    /**
     * 1 Optional.of(T t)：创建一个 Optional 实例
     */
    @Test
    public void test01(){
        Fruit fruit = new Fruit();
        Optional<Fruit> fruit1= Optional.of(fruit);
        System.out.println(fruit1.get());
        fruit = null;
        Optional<Fruit> fruit2 = Optional.of(fruit);
        // of 传入 null，使用 get() 报错 NullPointerException
        System.out.println(fruit2.get());
    }

    /**
     * 2 Optional.empty()：创建一个空的 Optional 实例
     */
    @Test
    public void test02(){
        Optional<Object> empty = Optional.empty();
        System.out.println(empty.get());
    }

    /**
     * isPresent()：判断容器中是否包含值
     */
    @Test
    public void test03(){
        // isPresent 传入 null
        Optional<Fruit> fruitOptional = Optional.ofNullable(null);
        if (fruitOptional.isPresent()){
            System.out.println("********* isPresent 传入 null *********");
            System.out.println(fruitOptional.get());
        }
        // isPresent 传入非 null
        Optional<Fruit> fruitOptional1 = Optional.ofNullable(new Fruit());
        if (fruitOptional1.isPresent()){
            System.out.println("*************** isPresent 传入非 null *************");
            System.out.println(fruitOptional1.get());
        }
    }

    /**
     * ofNullable  和 orElse
     */
    @Test
    public void test04(){
        Fruit fruit = new Fruit();
        System.out.println("******** ofNullable 传入非 null    **********");
        Optional<Fruit> fruit1 = Optional.ofNullable(fruit);
        Fruit fruit2 = (Fruit) fruit1.orElse(new Fruit("a"));
        System.out.println(fruit2);
        System.out.println("******** ofNullable 传入 null   **********");
        fruit = null;
        Optional<Fruit> fruit3 = Optional.ofNullable(fruit);
        Fruit fruit4 = (Fruit) fruit3.orElse(new Fruit("我是null"));
        System.out.println(fruit4);
    }


}
